//
//  OonlineViewController.m
//  Molian
//
//  Created by 胡津 on 30/6/15.
//  Copyright (c) 2015年 xiaocan. All rights reserved.
//

#import "OonlineViewController.h"
#import "MLUserDataViewController.h"//用户资料
#import "SRRefreshView.h" //下拉刷新
#import "OonlineCell.h"//本页面cell
#import "UIScrollView+DXRefresh.h"//上拉

#import "MeViewController.h"
#import "MLHomeViewController.h"
#import "MLTabBar.h"
#import "ArticleViewController.h"


#import "OnlineMenuView.h"
#import <CoreLocation/CoreLocation.h>
#import "SelectCityView.h"
// 每次拉取的用户数目
#define USER_NUM_PER_TIME 20

@interface OonlineViewController ()<SRRefreshDelegate,OnlineMenuViewDelegate,CLLocationManagerDelegate,SelectCityViewDelegate>


// 用户列表
@property (nonatomic, strong)NSMutableArray *userList;
// 最近刷新的时间
@property (nonatomic, strong)NSDate *lastRefreshTime;

//下拉刷新
@property (strong, nonatomic) SRRefreshView *slimeView;

// 当前分页
@property NSUInteger currentPage;

//筛选的view
//@property (nonatomic,assign)NSInteger first;
//@property (nonatomic,assign)NSInteger second;
//@property (nonatomic,assign)BOOL isLove;
//@property (nonatomic,assign)BOOL isSelect;

@property (nonatomic, strong)OnlineMenuView *menuView;//菜单
@property (nonatomic, strong)SelectCityView *selectCityView;//

//@property (strong, nonatomic) CLLocationManager *locationManager;//定位
//@property (nonatomic) BOOL isL;//判断有没有定位成功过

//@property (nonatomic) BOOL isClickL;//是选择按距离排,但是没有定位成功的时候使用判断

//@property (nonatomic, strong) AVGeoPoint *geoPoint;
//@property (nonatomic, strong) UIButton *cityBt;,去掉左上角定位




@end

@implementation OonlineViewController
{
    NSArray *typArr;
}

- (void)filterUser
{
    self.selectCityView.alpha = 0;
    if (self.menuView.alpha == 0) {
        [Utils Hidden:self.menuView Bool:YES];
    }else{
        [Utils Hidden:self.menuView Bool:NO];
    }
    
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:RGBA(31, 30, 30, 0.99)] forBarMetrics:UIBarMetricsDefault];
    
    if([ShareData shareData].isLike){
        [self.tableView reloadData];
        [ShareData shareData].isLike = NO;
    }
//    if(self.isL){
//        
//    }else{
//        if ([MLUser currentUser]) {
//            
//            [self startLocation];
//        }
//    }
    
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    //[Utils Hidden:self.selectView Bool:NO];
    self.menuView.alpha = 0;
}
//
//- (void)startLocation
//{
//    // 判断定位操作是否被允许
//    if([CLLocationManager locationServicesEnabled]) {
//        
//        //定位初始化
//        _locationManager=[[CLLocationManager alloc] init];
//        _locationManager.delegate=self;
//        _locationManager.desiredAccuracy=kCLLocationAccuracyBest;
//        _locationManager.distanceFilter=10;
//        
//        if([[[UIDevice currentDevice] systemVersion] floatValue]>=8.0){
//            [_locationManager requestWhenInUseAuthorization];
//        }
//        
//        [_locationManager startUpdatingLocation];//开启定位
//    }
//}
////定位错误
//-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
//{
//    [self.locationManager stopUpdatingLocation];
//    
//    [HUD hideFromViewAnimated:YES];
//    //
//}
//定位代理经纬度回调
//-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
//    
//    
//    [self.locationManager stopUpdatingLocation];
//    NSLog(@"location ok");
//    // [HUD hideFromViewAnimated:YES];
//    //    NSLog(@"%@",[NSString stringWithFormat:@"经度:%3.5f\n纬度:%3.5f",newLocation.coordinate.latitude,newLocation.coordinate.longitude]);
//    
//    self.geoPoint = [AVGeoPoint geoPointWithLatitude:newLocation.coordinate.latitude longitude:newLocation.coordinate.longitude];
//    self.isL = YES;
//    if (self.isClickL) {
//        //是选择过的,开始请求
//        
//         [self loadUserDataPage];
//        
//    }
//    
//    
//    MLUser *u = [MLUser currentUser];
//    if (u) {
//        u.geoPoint = [AVGeoPoint geoPointWithLatitude:newLocation.coordinate.latitude longitude:newLocation.coordinate.longitude];
//        
//        [u saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
//           
//        }];
//    }
//    
//    
//    
//}
-(void)toggleView
{
    if (self.menuView.alpha == 0) {
        [Utils Hidden:self.menuView Bool:YES];
    }else{
        [Utils Hidden:self.menuView Bool:NO];
    }
}
- (void)clickListButton
{
    
    

    
    
    //self.isSelect = YES;
   [self findRefreshUsers];
    [Utils Hidden:self.menuView Bool:NO];
}

//右上角初始化
-(void)rightItemTitle:(NSString*)title
{

    UIBarButtonItem *rightItem  = [[UIBarButtonItem alloc]initWithTitle:title style:UIBarButtonItemStylePlain target:self action:@selector(rightItem:)];
    
    self.navigationItem.rightBarButtonItem = rightItem;
}


//右上角item触发方法
- (void)rightItem:(UIBarButtonItem*)sender
{
    
    [self filterUser];
    
   
}
//选择城市
- (void)clickLeftBt
{
    
    [self filterCity];
    
}
- (void)clickCity:(NSString *)city
{
    [Utils saveToDefaults:city forKey:@"selectCity"];
    
    //选择城市后
 //    [self.cityBt setTitle:city forState:UIControlStateNormal];
    [self findRefreshUsers];
}
- (void)filterCity
{
    self.menuView.alpha = 0;
    if (self.selectCityView.alpha == 0) {
        [Utils Hidden:self.selectCityView Bool:YES];
    }else{
        [Utils Hidden:self.selectCityView Bool:NO];
    }
    
}
#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"会员";
    
//    NSString *selectCity = [Utils defaultsForKey:@"selectCity"];
//    if (selectCity==nil||selectCity.length==0) {
//        
//        MLUser *u = [MLUser currentUser];
//        if (u!=nil&&u.selectCity!=nil&&u.selectCity.length) {
//            selectCity = u.selectCity;
//        }else{
//             selectCity = @"广州";
//        }
//        
//        
//       
//    }
    
    
//    self.cityBt = [UIButton buttonWithType:UIButtonTypeCustom];
//    [self.cityBt sizeToFit];
//    [self.cityBt setTitle:selectCity forState:UIControlStateNormal];
//    [self.cityBt setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    [self.cityBt setTitleColor:RGBA(188, 188, 188, 1) forState:UIControlStateHighlighted];
//   // [self.cityBt setContentMode:UIViewContentModeLeft];
//    [self.cityBt setImage:[UIImage imageNamed:@"drop_icon"] forState:UIControlStateNormal];
//    [self.cityBt setImageEdgeInsets:UIEdgeInsetsMake(-8, 30, -8, 0)];
//    [self.cityBt setTitleEdgeInsets:UIEdgeInsetsMake(0, -28, 0, 0)];
//    self.cityBt.titleLabel.font = kFont(13);
//    self.cityBt.frame = CGRectMake(0, 0, 50, 30);
//    //self.cityBt.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
//    [self.cityBt addTarget:self action:@selector(clickLeftBt) forControlEvents:UIControlEventTouchUpInside];
//    UIBarButtonItem *leftBarBt = [[UIBarButtonItem alloc] initWithCustomView:self.cityBt];
//    self.navigationItem.leftBarButtonItems = @[leftBarBt];
    
    [self rightItemTitle:@"筛选"];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = APPCOLORBACKGROUNDCOLOR(1);
    
    // 从导航条以下开始计算
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kNavigationBarHeight, DeviceWidth, DeviceHeight - kNavigationBarHeight-50) style:UITableViewStylePlain];
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.scrollsToTop = YES;
    self.tableView.separatorColor = RGBA(229, 229, 229, 1);//分隔条颜色
  //  self.tableView.contentInset = UIEdgeInsetsMake(0, 0,10, 0);//偏移量
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
    self.tableView.tableFooterView = [[UIView alloc] init];//不显示空的cell
    //    [self.tableView setSeparatorInset:UIEdgeInsetsMake(0, -20, 0, 0)];
    [self.view addSubview:self.tableView];
    

    
    //上拉加载
    [self.tableView addFooterWithTarget:self action:@selector(loadUserDataPage)];
    
    _slimeView = [[SRRefreshView alloc] init];
    _slimeView.delegate = self;
    _slimeView.upInset = 0;
    _slimeView.slimeMissWhenGoingBack = YES;
    _slimeView.slime.bodyColor = APPCOLOR(1);
    _slimeView.slime.skinColor = [UIColor whiteColor];
    _slimeView.slime.lineWith = 1;
    _slimeView.slime.shadowBlur = 0;
    _slimeView.slime.shadowColor = [UIColor redColor];
    [self.tableView addSubview:self.slimeView];
    
    
//    if ([self.title isEqualToString:@"实习恋人"]) {
//        
//        if (![Utils cheackConfigurationScreen]) {
//            
//            
//        }
//        //self.isLove = NO;
//        self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 40, 0);//滚动条偏移量
//        self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);//偏移量
//        self.tableView.frame = CGRectMake(0, 0, DeviceWidth, DeviceHeight+40);
//        //self.isSelect = YES;
//    }else{
//        self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(64, 0, 50, 0);//滚动条偏移量
//        //self.isLove = YES;
//    }
   
    
    // 初始化用户列表
    self.userList = [[NSMutableArray alloc]init];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sliding:) name:@"sliding" object:nil];
    
    
    
    // 获取初始用户数据
    [self findRefreshUsers];
    
    self.menuView = [[OnlineMenuView alloc] initWithFrame:CGRectMake(0,0 , DeviceWidth, DeviceHeight)];
    self.menuView.delegate = self;
    [self.view addSubview:self.menuView];
    
    self.selectCityView = [[SelectCityView alloc] initWithFrame:CGRectMake(0, 0, DeviceWidth, DeviceHeight)];
    self.selectCityView.delegate = self;
    [self.view addSubview:self.selectCityView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(chatUserTypeDataChange:) name:@"chatUserTypeDataChange" object:nil];
    
    //用来加载好友关系
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tableViewReloadData) name:@"OnlineTableViewReloadData" object:nil];
    //把我的恋人从列表删除
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleMySweetheartOfUserList:) name:@"deleMySweetheartOfUserList" object:nil];
    
}
-(void)deleMySweetheartOfUserList:(NSNotification*)notification
{
    NSDictionary *dic=[notification userInfo];
    NSString *objectId = [dic objectForKey:@"objectId"];
    
    for (int i = 0; i<self.userList.count; i++) {
        MLUser *user = (MLUser *)[self.userList objectAtIndex:i];
        if (objectId&&user&&user.objectId&&[objectId isEqualToString:user.objectId]) {
            [self.userList removeObjectAtIndex:i];
            [self.tableView reloadData];
            break;
        }
    }
    
}
- (void)tableViewReloadData
{
    [self.tableView reloadData];
}

-(void)chatUserTypeDataChange:(NSNotification *)notification
{
    NSDictionary *dic=[notification userInfo];
    MLUser *chatUser = [dic objectForKey:@"user"];
    if (self.userList&&chatUser) {
        for (int i = 0; i<self.userList.count; i++) {
            MLUser *u = (MLUser *)self.userList[i];
            if ([u.objectId isEqualToString:chatUser.objectId]) {
                [self.userList replaceObjectAtIndex:i withObject:chatUser];
                break;
            }
        }
    }

}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    //    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"sliding" object:nil];
}
-(void)xsimge
{
    if ([Utils onePerform:@"xinshou22333"]) {
        UIView *xsview = [[UIView alloc]initWithFrame:self.view.frame];
        xsview.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.7];
        [[UIApplication sharedApplication].delegate.window addSubview:xsview];
    
    UIImage *image;
    if (IS_IPHONE_4) {
        image = [UIImage imageNamed:@"img_letter@640x960"];
    }else if (IS_IPHONE_5){
        image = [UIImage imageNamed:@"img_letter@640x1136"];
    }else if (IS_IPHONE_6){
        image = [UIImage imageNamed:@"img_letter@750x1334"];
    }else if (IS_IPHONE_6_PLUS){
        image = [UIImage imageNamed:@"img_letter@1242x2208"];
    }
        UIImageView *xsimge = [[UIImageView alloc]initWithFrame:self.view.frame];
        xsimge.image = image;
        [xsimge setContentMode:UIViewContentModeScaleAspectFill];
        [xsview addSubview:xsimge];
        [xsview addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(xsview:)]];
    }
}

- (void)xsview:(UITapGestureRecognizer*)top
{
    [top.view removeFromSuperview];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    // Dispose of any resources that can be recreated.
}

-(void)sliding:(NSNotification*)notification
{
    NSDictionary *dic=[notification userInfo];
    if ([[dic objectForKey:@"sliding"] isEqualToString:@"Start"]) {
        [self cellresetContainerView];
    }
}

#pragma mark - tableView delegate

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static  NSString *CellIdentifier = @"OonlineCell" ;
    // 自定义cell类
    OonlineCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if  (cell == nil) {
        cell = [[OonlineCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
        cell.tabbar = self.tabBarController;
        
    }
    
    
    // 获取当前cell
    if ([self.userList count]) {
        MLUser *showUser = self.userList[indexPath.row];
        cell.userLikeData = showUser;
        cell.userNameLabel.text = showUser.nickname;
        if (!showUser.subAvatar || [showUser.subAvatar isEqualToString:@""]) {
            [cell.userAvatarImg sd_setImageWithURL:[NSURL URLWithString:showUser.avatar.url] placeholderImage:[UIImage imageNamed:@"common_avatar_loading_background"]];
        }else{
            [cell.userAvatarImg sd_setImageWithURL:[NSURL URLWithString:showUser.subAvatar] placeholderImage:[UIImage imageNamed:@"common_avatar_loading_background"]];
        }

        
        [cell.userAgeLabel setTitle:[NSString stringWithFormat:@"%ld", (long)[showUser getUserAge]] forState:UIControlStateNormal];
        if (showUser.gender == MLUserGender_MALE) {
            [cell.userAgeLabel setBackgroundImage:[UIImage imageNamed:@"boy_age"] forState:UIControlStateNormal];
        } else {
            [cell.userAgeLabel setBackgroundImage:[UIImage imageNamed:@"girl_age"] forState:UIControlStateNormal];
        }
        
       // if (showUser.type != MLUserType_NORMAL) {
            cell.delegate = self;
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.backgroundColor = APPCOLOR(1);
            btn.tag = indexPath.row;
            [btn addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
            [btn setImage:[UIImage imageNamed:@"tuijian_icon"] forState:UIControlStateNormal];
            [btn setTitle:@"  会员故事" forState:UIControlStateNormal];
            [cell addActionButtons:@[btn] withButtonWidth:kJAButtonWidth withButtonPosition:JAButtonLocationLeft];
//        }else{
//            cell.delegate = nil;
//            [cell addActionButtons:@[] withButtonWidth:kJAButtonWidth withButtonPosition:JAButtonLocationLeft];
//        }
        
        
        cell.userInfo.text = [TimeUtils getPastTimeWithDate:showUser.lastLogin];
        cell.userSeriesLabel.selected = YES;
       // cell.RECOMMENDED.selected = showUser.type == 2;
        
        NSString *city = showUser.selectCity?showUser.selectCity:@"";
        NSString *strH = showUser.height?[NSString stringWithFormat:@"%ldcm",(long)showUser.height]:@"";
        NSString *title = [NSString stringWithFormat:@"%@  %@",city,strH];
        [cell.userSeriesLabel setTitle:title forState:UIControlStateNormal];
        cell.userSignatureLabel.text = showUser.intro;
        NSString *str = [[ShareData shareData].likeUserDic objectForKey:showUser.objectId];
        
        cell.userLikeBtn.Title.text =  str;
        
        //MLTabBar *tabBar = (MLTabBar *)self.tabBarController;
        //  MLHomeViewController *homeView = (MLHomeViewController *)tabBar.homeNavigation.topViewController;
        //  self.likeUsers = [ShareData shareData].likeUsers;
        // 设置喜欢的人状态
        BOOL isLiked = NO;
        
        if([Utils isLoveUserObjectId:showUser.objectId]){
            isLiked = YES;
        }
        if (!isLiked) {
            [cell.userLikeBtn Like:NO Alpha:0.4];
            cell.userLikeBtn.status = NO;
        }else{
            [cell.userLikeBtn Like:YES Alpha:0.4];
            cell.userLikeBtn.status = YES;
        }
        [cell.userLikeBtn layoutSubviews];
        
        
    }
    cell.backgroundColor = RGBA(249, 249, 249, 1);
    
    return  cell;
    
    //    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (_slimeView) {
        [_slimeView scrollViewDidScroll];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [self cellresetContainerView];
    if (_slimeView) {
        [_slimeView scrollViewDidEndDraging];
    }
}

//cell点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
     [AVAnalytics event:@"空闲恋人个人资料页面访问"]; // 通知服务器一个like点击事件。
//    if (self.isLove) {
//        [AVAnalytics event:@"空闲恋人个人资料页面访问"]; // 通知服务器一个like点击事件。
//    }else{
//        [AVAnalytics event:@"实习恋人个人资料页面访问"]; // 通知服务器一个like点击事件。
//    }
    MLUser *showUser = self.userList[indexPath.row];
    MLUserDataViewController *userInfoVC = [[MLUserDataViewController alloc]init];
    userInfoVC.userData = showUser;
    userInfoVC.redact = YES;
    //    userInfoVC.likeUsers = self.likeUsers;
    [Utils pushTabbarHidden:userInfoVC Selfvc:self];
    
}

//cell数目
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.userList count];
}

//设置行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 85;
}

//专属恋人点击事件
-(void)buttonTapped:(UIButton *)btn
{
    OonlineCell *cell = (OonlineCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:btn.tag inSection:0]];
    [self bianjituijian:cell];
    
}


#pragma mark - JASwipeCell delegate

// 打开右滑左边专属恋人视图关闭已经打开的专属恋人
- (void)swipingRightForCell:(OonlineCell *)cell
{
    NSArray *indexPaths = [self.tableView indexPathsForVisibleRows];
    
    for (int i = 1; i<indexPaths.count; i++) {
        NSIndexPath *indexPath = indexPaths[i];
        JASwipeCell *visibleCell = (JASwipeCell *)[self.tableView cellForRowAtIndexPath:indexPath];
        if (visibleCell != cell) {
            [visibleCell resetContainerView];
        }
    }
}

//一次滑到底执行
- (void)leftMostButtonSwipeCompleted:(OonlineCell *)cell
{
    [self bianjituijian:cell];
}

-(void)bianjituijian:(OonlineCell *)cell
{
    OonlineCell *cell2 = (OonlineCell *)cell;
    MLArticle *articele = cell2.userLikeData.belongToArticle;
    if (cell2.userLikeData.belongToArticle ) {
        ArticleViewController *articleViewController = [[ArticleViewController alloc]init];
        articleViewController.article = articele;
        articleViewController.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:articleViewController animated:YES];
        [self cellresetContainerView];
    }else{
        [self cellresetContainerView];
        [HUD Prompt:@"该会员故事正在编辑，即将上线"];
    }
    
}
//滑动视图执行关闭左侧视图
#pragma mark - UIScrollViewDelegate methods

-(void)cellresetContainerView
{
    NSArray *indexPaths = [self.tableView indexPathsForVisibleRows];
    
    for (int i = 1; i<indexPaths.count; i++) {
        NSIndexPath *indexPath = indexPaths[i];
        JASwipeCell *cell = (JASwipeCell *)[self.tableView cellForRowAtIndexPath:indexPath];
        if ([cell leftButtonsRevealed]) {
            [cell resetContainerView];
        }
    }
}

#pragma mark - refresh data

// 刷新用户
- (void)findRefreshUsers {
    // 设置刷新时间
    self.lastRefreshTime = [NSDate date];
    // 当前分页归零
    self.currentPage = 0;
    // 加载用户数据
    [AVAnalytics event:@"空闲恋人刷新"]; // 通知服务器一个like点击事件。
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if([ShareData shareData].sweetheartType == sweetheartType_NO){
            
        }else{
            NSInteger number = 0;
            if ([ShareData shareData].firstView.sweetheart) {
                number++;
            }
            if ([ShareData shareData].secondView.sweetheart) {
                number++;
            }
            if ([ShareData shareData].thirdView.sweetheart) {
                number++;
            }
            if(number<3){
                [AVCloud callFunctionInBackground:@"getNetTime" withParameters:nil block:^(id objectt, NSError *errorr) {
                    if (!errorr) {
                        NSString *str = objectt;
                        NSDate *date = [NSDate dateWithTimeIntervalSince1970:[str longLongValue]/1000];
                        MLUser *user = [MLUser currentUser];
                        user.lastLogin = date;
                        [user saveInBackground];
                        
                    }else{
                        
                    }
                    
                }];
            }
            
        }
    });
    
    
    
    
    
       [self loadUserDataPage];

}

- (void)slimeRefreshStartRefresh:(SRRefreshView *)refreshView
{
    [self findRefreshUsers];
}

// 加载用户信息
- (void)loadUserDataPage{
    
    
    NSInteger gender = 0;
    NSString *city;
    NSDictionary *dic = [Utils screenRecord];
    if (dic) {
        gender = [[dic objectForKey:@"sex"] integerValue];
        //userType = [[dic objectForKey:@"userType"] integerValue];//筛选普通用户//现在是距离和登录时间
        //2 ,0登录时间,, 1是距离
        city = [dic objectForKey:@"city"];
        if (city == nil||city.length == 0) {
            city = @"不限";
        }
        
        
    }else{
        gender = 0;
     //   userType = 0;//筛选普通用户
        city = @"不限";
    }
    
//    if (userType == 1) {
        //是定位的
        //判断是否定位过
    //城市是默认的,则需要定位
//    if([city isEqualToString:@"不限"]){
//        if(self.isL){
//            self.isClickL = NO;
//            //定位成功
//            
//        }else{
//            //定位失败.开始定位
//            self.isClickL = YES;
//            [self startLocation];
//            return;
//        }
//    }
    
    
        
//    }else{
//      
//        
//    }
   
    
    
    
    [HUD setOnViewWithTitle:@"请求中" animated:YES];
    // 分页查找最近登录的用户资料
    // TODO 根据性别&&位置&&禁止的人筛选
    AVQuery *userQuery = [MLUser query];
    [userQuery whereKey:@"isUserInited"  equalTo:[NSNumber numberWithInteger:1]];
    
//    现在改成选择城市
    
    if(city == nil||[city isEqualToString:@"不限"]||[city isEqualToString:@"全国"]){
        
    }else{
        [userQuery whereKey:@"selectCity" equalTo:city];
    }
    
//    NSString *selectCity = [Utils defaultsForKey:@"selectCity"];
//    if (selectCity==nil||selectCity.length==0) {
//        selectCity = @"广州";
//    }
//    if([selectCity isEqualToString:@"全部"]){
//        
//    }else{
//        
//        NSLog(@"%@",selectCity);
//        [userQuery whereKey:@"selectCity" equalTo:selectCity];
//    }
    
    NSArray *statusArr = [NSArray arrayWithObjects:[NSNumber numberWithInteger:MLUserStatus_WARNING],[NSNumber numberWithInteger:MLUserStatus_DISABLE], nil];
    // //被警告用户不能出现在恋人列表
   // [userQuery whereKey:@"status" notEqualTo:[NSNumber numberWithInteger:MLUserStatus_WARNING]];
    //被封号
   // [userQuery whereKey:@"status" notEqualTo:[NSNumber numberWithInteger:MLUserStatus_DISABLE]];
    
    
//    if(userType == 1){
//        //按距离
//        if (self.isL) {
//            [userQuery whereKey:@"geoPoint" nearGeoPoint:self.geoPoint];
//        }else{
//            [HUD Prompt:@"定位失败,默认按登录时间排序"];
//            [Utils screenRecordSex:gender userType:0];
//            [userQuery orderByDescending:@"lastLogin"];
//        }
//    }else{
           [userQuery orderByDescending:@"lastLogin"];
//    }
    
    
    [userQuery whereKey:@"status" notContainedIn:statusArr];
    
    if (gender !=0) {
        //性别
        [userQuery whereKey:@"gender" equalTo:[NSNumber numberWithInteger:gender]];
    }
//    [userQuery whereKey:@"type" equalTo:[NSNumber numberWithInteger:userType]];
    //    [userQuery whereKey:@"lastLogin" lessThanOrEqualTo:self.lastRefreshTime];
//    if (self.isSelect == YES) {
//        if(self.first != 0){
//            //性别
//            [userQuery whereKey:@"gender" equalTo:[NSNumber numberWithInteger:self.first]];
//        }
//        if (self.second !=0 && u.location_city && u.location_city.length) {
//            //是同城
//            [userQuery whereKey:@"location_city" equalTo:u.location_city];
//        }
//    }
    
//    if (self.isLove) {
//        [userQuery whereKey:@"type" notEqualTo:[NSNumber numberWithInteger:MLUserType_NORMAL]];
//    }else{
//        [AVAnalytics event:@"实习恋人页面刷新"]; // 通知服务器一个like点击事件。
//        [userQuery whereKey:@"type" equalTo:[NSNumber numberWithInteger:MLUserType_NORMAL]];
//    }
    [AVAnalytics event:@"空闲恋人页面刷新"];
    //特殊字段
    if ([Utils cheackConfigurationScreen]) {
      // [userQuery whereKey:@"checkappOther" equalTo:[NSNumber numberWithInteger:1]];
    }else{
       
    }
 
    [userQuery includeKey:@"belongToArticle"];
    // 控制分页获取
    userQuery.limit = USER_NUM_PER_TIME;
    userQuery.skip = self.currentPage * USER_NUM_PER_TIME;
    // 异步查询符合条件的用户, 添加到用户列表中
    userQuery.cachePolicy = kAVCachePolicyNetworkElseCache;
    userQuery.maxCacheAge = 7200;
    [userQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        [HUD hideFromViewAnimated:YES];
        //停止加载
        [_slimeView endRefresh];
        [Utils playWavName:@"add"];
        [self.tableView footerEndRefreshing];
        if (!error) {
            if(self.currentPage == 0){
                if (objects.count == 0) {
                    [HUD Prompt:@"当前选择无数据,默认选择全国"];
                    [self.menuView cityNoHuman];
                    [self loadUserDataPage];
                    
                    
                }
                // 清除所有已加载的用户
                [self.userList removeAllObjects];
            }
            
             NSArray *arr = [NSArray arrayWithArray:[self deleteRepetitiveArr:objects]];
            [self.userList addObjectsFromArray:arr];
            [self deleteMySweetheart];
            
            for (int i = 0; i<arr.count; i++) {
                MLUser *u =(MLUser *)arr[i];
                [[ShareData shareData].likeUserDic setObject:[NSString stringWithFormat:@"%ld",(long)u.likeCount] forKey:u.objectId];
            }
            // 增加分页
            self.currentPage ++;
            // 刷新列表显示
            [self.tableView reloadData];
        } else {
            // 加载出错, 提示
            [HUD Prompt:@"网络异常"];
        }
    }];
}
- (void)deleteMySweetheart
{
    ShareData *sharedata = [ShareData shareData];
    if (sharedata.firstView.sweetheart) {
        [self deleteMySweetheartObjectId:sharedata.firstView.sweetheartUser.objectId];
        
    }
    if (sharedata.secondView.sweetheart) {
        [self deleteMySweetheartObjectId:sharedata.secondView.sweetheartUser.objectId];
        
    }
    if (sharedata.thirdView.sweetheart) {
        [self deleteMySweetheartObjectId:sharedata.thirdView.sweetheartUser.objectId];
        
    }
    
}
- (void)deleteMySweetheartObjectId:(NSString *)objectId
{
    for (int i = 0; i<self.userList.count; i++) {
        MLUser *user = (MLUser *)[self.userList objectAtIndex:i];
        if (objectId&&user&&user.objectId&&[objectId isEqualToString:user.objectId]) {
            [self.userList removeObjectAtIndex:i];
        }
    }
}
//删除重复的用户
- (NSMutableArray *)deleteRepetitiveArr:(NSArray *)objects
{
    
    NSMutableArray *arr = [NSMutableArray arrayWithArray:objects];
    
    for (int j = 0; j<self.userList.count; j++) {
        MLUser *user = (MLUser *)[self.userList objectAtIndex:j];
        for (int i = 0; i<arr.count; i++) {
            MLUser *nUser = (MLUser *)[arr objectAtIndex:i];
            if ([user.objectId isEqualToString:nUser.objectId]) {
                [arr removeObjectAtIndex:i];
                i--;
            }
        }
    }
    
    return arr;
    
}
@end
